﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using EqRepair.Code.Classes;
using EqRepair.Code.Data;

namespace EqRepair.Web
{
	public partial class EquipmentDetail : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
				if (IsPostBack) return;
				//lstAllEquipment.Items.Clear();
				FillAllComponents();
				btnUpdateEq.Visible = !(btnAddEq.Visible = String.IsNullOrEmpty(Request["id"]));
				if (String.IsNullOrEmpty(Request["id"])) return;
				FillCurComponents();
				using (var db = new DataClasses2DataContext())
				{
					var eq = db.Equipments.First(x => x.Id == Int32.Parse(Request["id"]));
					txtName.Text = eq.Name;
					txtDescription.Text = eq.Description;
					txtCost.Text = eq.RepairCost.ToString();
					txtLifeTime.Text = eq.LifeTime.ToString();
					txtRepairTime.Text = eq.RepairTime.ToString();
					hfId.Value = Request["id"];
					UpdateTreeDet();
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Произошла непредвиденная ошибка. " + ex.Message, "Внимание.", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
			}

		}

		private void FillAllComponents()
		{
			using (var db = new DataClasses2DataContext())
			{
				var allEq = db.Equipments.OrderBy(x => x.Name);
				foreach (var equipment in allEq)
					lstAllEquipment.Items.Add(new ListItem(equipment.Name, equipment.Id.ToString()));
			}
		}

		private void FillCurComponents()
		{
			lstCurrentEquipment.Items.Clear();
			using (var db = new DataClasses2DataContext())
			{
				var currentEqs = db.Equipments.First(x => x.Id == Int32.Parse(Request["id"])).EquipmentHierarchies1;
				foreach (var currentEq in currentEqs)
					lstCurrentEquipment.Items.Add(new ListItem(String.Format("{0} ({1})", currentEq.Equipment.Name, currentEq.Count),
															   currentEq.ChildEquipmentId.ToString()));
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			
			var selectedEq = lstAllEquipment.SelectedItem;
			if (selectedEq != null)
			{
				var presentItem = lstCurrentEquipment.Items.FindByValue(selectedEq.Value);
				if (presentItem == null)
					lstCurrentEquipment.Items.Add(new ListItem(String.Format("{0} ({1})", selectedEq.Text, 1), selectedEq.Value));
				else
				{
					var index = presentItem.Text.LastIndexOf('(');
					var count = Int32.Parse(presentItem.Text.Substring(index + 1, presentItem.Text.Length - index - 2));
					lstCurrentEquipment.Items[lstCurrentEquipment.Items.IndexOf(presentItem)].Text = String.Format("{0} ({1})",
					                                                                                               selectedEq.Text,
					                                                                                               count + 1);
				}
			    UpdateTreeDet();
			}
		}

	    public void UpdateTreeDet()
	    {
            int idi = Int32.Parse(Request["id"]);
            TreeViewDet.Nodes.Clear();
            TreeViewDet.Nodes.Add(AccessData.GetTreeAgregInEq(idi));
            TreeViewDet.ExpandAll();
	    }

	    protected void btnDel_Click(object sender, EventArgs e)
		{
			var selectedEq = lstCurrentEquipment.SelectedItem;
			if (selectedEq != null)
			{
				var index = selectedEq.Text.LastIndexOf('(');
				var count = Int32.Parse(selectedEq.Text.Substring(index + 1, selectedEq.Text.Length - index - 2));
				if (count > 1)
					lstCurrentEquipment.Items[lstCurrentEquipment.Items.IndexOf(selectedEq)].Text =
						String.Format("{0} ({1})", selectedEq.Text.Substring(0, index - 1), count - 1);
				else
					lstCurrentEquipment.Items.Remove(selectedEq);
			}
            UpdateTreeDet();
		}

		protected void btnAddEq_Click(object sender, EventArgs e)
		{

		}

		protected void btnUpdateEq_Click(object sender, EventArgs e)
		{
		    SaveAll();
            UpdateTreeDet();
		}
        public void SaveAll()
        {
			try
			{
				using (var db = new DataClasses2DataContext())
				{
					int idi = Int32.Parse(Request["id"]);
					db.EquipmentHierarchies.DeleteAllOnSubmit(db.EquipmentHierarchies.Where(x => x.ParentEquipmentId == idi));
					db.SubmitChanges();
					foreach (ListItem it in lstCurrentEquipment.Items)
					{
						var index = it.Text.LastIndexOf('(');
						var count = Int32.Parse(it.Text.Substring(index + 1, it.Text.Length - index - 2));
						db.EquipmentHierarchies.InsertOnSubmit(new EquipmentHierarchy
						                                       	{
						                                       		ParentEquipmentId = idi,
						                                       		ChildEquipmentId = Int32.Parse(it.Value),
						                                       		Count = count
						                                       	});
						db.SubmitChanges();
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Произошла непредвиденная ошибка. " + ex.Message, "Внимание.", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
			}

        }
	}
}